package com.codefish.codefishseckill.security;

import com.codefish.codefishseckill.utils.MD5PasswordUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

/**
 * @author <a href='https://gitee.com/hzf2281'>codefish</a>
 * @version 1.0.0
 * @since 2022/08/30 下午 04:53
 */
@Slf4j
@Component
public class MyPasswordEncoder implements PasswordEncoder {

    @Override
    public String encode(CharSequence rawPassword) {
        String str = rawPassword.toString();
        String salt = MD5PasswordUtil.randSalt(5);
        return MD5PasswordUtil.secretPasswordToDBPassword(str, salt);
    }

    @Override
    public boolean matches(CharSequence rawPassword, String encodedPassword) {
        String[] strs = MD5PasswordUtil.getPasswordAndSalt(encodedPassword);
        String epassword = strs[0];
        String salt = strs[1];

        log.debug("加密后的密码为：{},盐值为：{}", epassword, salt);

        //这里双重加密需要设为false，因为拿到的rawPassword已经在前端做了加密
        return MD5PasswordUtil.verifyPassword(rawPassword.toString(), epassword, salt, false);
    }


}
